package com.hzit.dao.base;

import java.sql.*;

public class BaseDao {


    /**
     * 获取连接
     *
     * @return
     */
    protected Connection getConnection() {

        //1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");

            //2.获取连接
            String url = "jdbc:mysql://localhost:3306/bj2004?characterEncoding=utf8&useSSL=true";
            String username = "root";
            String password = "root";
            Connection connection = DriverManager.getConnection(url, username, password);

            //3.返回
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("获取连接失败.....");
        }
        return null;
    }


    /**
     * 公共的增删改操作
     *
     * @param sql
     * @param param
     * @return
     */
    protected int baseExecuteUpdate(String sql, Object... param) {

        Connection connection = this.getConnection();
        PreparedStatement preparedStatement = null;

        try {
            preparedStatement = connection.prepareStatement(sql);

            // 占位符赋值
            if (param != null && param.length != 0) {
                for (int i = 0; i < param.length; i++) {
                    preparedStatement.setObject(i + 1, param[i]);
                }
            }
            int row = preparedStatement.executeUpdate();

            return row;

        } catch (SQLException e) {
            System.err.println("baseExecuteUpdate公共增删改方法异常.....");
            e.printStackTrace();
        } finally {
            this.closeAll(null, preparedStatement, connection);
        }
        return 0;
    }

    /**
     * 关闭资源
     *
     * @param rs
     * @param statement
     * @param connection
     */
    protected void closeAll(ResultSet rs, Statement statement, Connection connection) {

        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
